package com.sysu.simulation;

import android.content.Context;
import android.content.Intent;
import android.renderscript.Double2;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sysu.simulation.bean.User;
import com.sysu.simulation.helper.AccountHelper;
import com.sysu.simulation.helper.ApiHelper;
import com.sysu.simulation.helper.NetworkHelper;

import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class EditUserActivity extends BaseActivity implements View.OnClickListener{

    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.edit_height)
    EditText mEditHeight;
    @BindView(R.id.edit_weight)
    EditText mEditWeight;
    @BindView(R.id.radioGroup_gender)
    RadioGroup mRadioGroup;
    @BindView(R.id.radio_male)
    RadioButton mRadioMale;
    @BindView(R.id.radio_female)
    RadioButton mRadioFemale;
    @BindView(R.id.progress_edit_user)
    ProgressBar mProgressBar;

    private User mUser;
    private User editUser;
    private Toast mToast;

    @Override
    protected void initWindow() {
        super.initWindow();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(false);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mUser = AccountHelper.getUser();
        if(mUser.getId()!=null) mEditName.setText(mUser.getNickname());
        if(mUser.getHeight()!=0) mEditHeight.setText(String.valueOf(mUser.getHeight()));
        if(mUser.getWeight()!=0) mEditWeight.setText(String.valueOf(mUser.getWeight()));
        if(mUser.getGender()==0) mRadioMale.setChecked(true);
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return super.onSupportNavigateUp();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public static void show(Context context) {
        context.startActivity(new Intent(context, EditUserActivity.class));
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_edit_user;
    }

    @OnClick(R.id.submit_edit_user)
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.submit_edit_user:
                attemptEdit();
                break;
            default:
                break;
        }
    }

    private void attemptEdit() {
        mEditName.setError(null);
        mEditHeight.setError(null);
        mEditWeight.setError(null);

        String newName = mEditName.getText().toString().trim();
        String newHeight = mEditHeight.getText().toString().trim();
        String newWeight = mEditWeight.getText().toString().trim();
        int newGender = 2;
        if(mRadioMale.isChecked()) newGender = 0;
        if(mRadioFemale.isChecked()) newGender = 1;

        boolean cancel = false;
        View focusView = null;

        if(newGender==2) {
            focusView = mRadioGroup;
            cancel = true;
        }

        if (TextUtils.isEmpty(newWeight)) {
            mEditWeight.setError(getString(R.string.error_field_required));
            focusView = mEditWeight;
            cancel = true;
        }

        if (TextUtils.isEmpty(newHeight)) {
            mEditHeight.setError(getString(R.string.error_field_required));
            focusView = mEditHeight;
            cancel = true;
        }

        if (TextUtils.isEmpty(newName)) {
            mEditName.setError(getString(R.string.error_field_required));
            focusView = mEditName;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            if(NetworkHelper.hasInternet(this)) {
                doEdit(newName, newHeight, newWeight, newGender);
            }
            else {
                showToast("未连接网络");
            }
        }
    }

    private void doEdit(String name, String height, String weight, int gender) {
        editUser = new User();
        editUser.setId(mUser.getId());
        editUser.setNickname(name);
        editUser.setHeight(Integer.parseInt(height));
        editUser.setWeight(Integer.parseInt(weight));
        editUser.setGender(gender);

        String info = new Gson().toJson(editUser);

        ApiHelper.editInfo(info, new TextHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                showProgressBar(null);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideProgressBar();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                hideProgressBar();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast("网络请求错误，请重试。");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                if(responseString.equals("failed")) {
                    showToast("修改失败，请重试。");
                    return;
                }

                if(AccountHelper.updateUserCache(editUser)) {
                    finish();
                }
                else {
                    showToast("本地更新失败。");
                }
            }
        });
    }

    private void showProgressBar(String msg) {
        mProgressBar.setVisibility(View.VISIBLE);
    }

    private void hideProgressBar() {
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    private void showToast(String msg) {
        if(mToast==null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        }
        mToast.setText(msg);
        mToast.show();
    }
}
